package com.example.jpetstoreclient.controller;

import com.example.jpetstoreclient.common.CommonResponse;
import com.example.jpetstoreclient.domain.CartItem;
import com.example.jpetstoreclient.domain.Order;
import com.example.jpetstoreclient.service.CartItemService;
import com.example.jpetstoreclient.service.OrderService;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Validated
@CrossOrigin
@RestController
@RequestMapping("/cart")
public class CartItemController {
    @Autowired
    private CartItemService cartItemService;
    @Autowired
    private OrderService orderService;

    //  返回用户的所有购物车商品
    @GetMapping("/{id}")
    public CommonResponse<List<CartItem>> getAll(@PathVariable("id") int userId){
        return cartItemService.getAllCartItems(userId);
    }

    //  删除购物车商品
    @DeleteMapping("/delete/{id}")
    public CommonResponse<Object> delete(@PathVariable("id") @NotBlank(message = "删除的购物车不能为空") int cartId){
        return cartItemService.deleteCartItem(cartId);
    }

    //  更新购物车商品信息
    @PutMapping("/update")
    public CommonResponse<CartItem> update(@RequestBody CartItem cartItem){
        if (cartItemService.updateById(cartItem)){
            return CommonResponse.createForSuccessMessage("修改购物车商品信息成功");
        }
        return CommonResponse.createForError("修改购物车商品信息失败");
    }

    //  新增购物车商品
    @PostMapping("/save")
    public CommonResponse<Object> save(@RequestBody CartItem cartItem){
        return cartItemService.addCartItem(cartItem);
    }

    //  提交购物车订单
    @PostMapping("/submit")
    public CommonResponse<List<Order>> submit(@RequestParam("cart_id") @NotNull(message = "下单商品不能为空") List<Integer> cart_ids,
                                           @RequestParam("user_id") @NotNull(message = "下单用户不能为空") int user_id,
                                           @RequestParam("remark") String remark,
                                           @RequestParam("address") @NotBlank(message = "地址不能为空") String address){
        return orderService.generateOrders(cart_ids, user_id, remark, address);
    }
}
